<template>
  <div class="register-form">
    <a-form
      :model="form"
      :rules="rules"
      @finish="handleRegister"
      layout="vertical"
    >
      <!-- <a-form-item label="用户名" name="username">
        <a-input
          v-model:value="form.username"
          placeholder="请输入用户名"
          size="large"
        />
      </a-form-item> -->

      <a-form-item label="手机号" name="phone">
        <a-input
          v-model:value="form.phone"
          placeholder="请输入手机号"
          size="large"
        />
      </a-form-item>

      <a-form-item label="验证码" name="code">
        <div class="code-input-group">
          <a-input
            v-model:value="form.code"
            placeholder="请输入验证码"
            size="large"
            style="flex: 1;"
          />
          <a-button
            type="primary"
            size="large"
            :loading="sendingCode"
            :disabled="!form.phone || countdown > 0"
            @click="sendCode"
            style="margin-left: 8px;"
          >
            {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
          </a-button>
        </div>
      </a-form-item>

      <!-- <a-form-item label="联系方式" name="contact">
        <a-input
          v-model:value="form.contact"
          placeholder="请输入联系方式（QQ或微信）"
          size="large"
        />
      </a-form-item> -->

      <a-form-item label="密码" name="password">
        <a-input-password
          v-model:value="form.password"
          placeholder="请输入密码"
          size="large"
        />
      </a-form-item>

      <a-form-item label="确认密码" name="confirmPassword">
        <a-input-password
          v-model:value="form.confirmPassword"
          placeholder="请再次输入密码"
          size="large"
        />
      </a-form-item>

      <a-form-item label="邀请码（可选）" name="inviteCode">
        <a-input
          v-model:value="form.inviteCode"
          placeholder="请输入邀请码"
          size="large"
          :disabled="inviteCodeFromUrl"
        />
        <div v-if="inviterInfo" class="inviter-info">
          <span class="inviter-tip">邀请者：{{ inviterInfo.username }}</span>
        </div>
      </a-form-item>

      <a-form-item>
        <a-button
          type="primary"
          html-type="submit"
          :loading="loading"
          size="large"
          block
        >
          注册
        </a-button>
      </a-form-item>

      <a-form-item>
        <div class="form-footer">
          <span>已有账号？</span>
          <a @click="$emit('switch-to-login')">立即登录</a>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import authAPI from '~/api/auth'
import { getInviterInfo } from '~/api/invite.js'

const emit = defineEmits(['success', 'switch-to-register'])
const userStore = useUserStore()

// 表单数据
const form = reactive({
  phone: '',
  code: '',
  password: '',
  confirmPassword: '',
  inviteCode: ''
})

// 表单验证规则
const rules = {
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
  ],
  code: [
    { required: true, message: '请输入验证码' },
    { pattern: /^\d{4,6}$/, message: '验证码格式不正确' }
  ],
  password: [
    { required: true, message: '请输入密码' },
    { min: 6, message: '密码至少6个字符' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码' },
    {
      validator: (rule, value) => {
        if (value !== form.password) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      }
    }
  ]
}

// 加载状态
const loading = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)
let countdownTimer = null

// 邀请码相关
const inviteCodeFromUrl = ref(false)
const inviterInfo = ref(null)
const route = useRoute()

// 发送验证码
const sendCode = async () => {
  if (!form.phone) {
    message.error('请先输入手机号')
    return
  }
  
  sendingCode.value = true
  try {
    const response = await authAPI.sendSmsCode({
      phone: form.phone,
      scene: 'register'
    })
    
    if (response.status === 'success') {
      message.success('验证码已发送')
      startCountdown()
    } else {
      message.error(response.message || '发送失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    message.error(error.message || '发送失败，请稍后重试')
  } finally {
    sendingCode.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer)
      countdownTimer = null
    }
  }, 1000)
}

// 处理注册
const handleRegister = async (values) => {
  loading.value = true
  try {
    const data = await authAPI.register(form)
    if (data.code === 200) {
      message.success('注册成功')
      userStore.setUserInfo(data.data.user)
      localStorage.setItem('user', JSON.stringify(data.data.user))
      localStorage.setItem('token', data.data.token)
      emit('success')
    } else {
      message.error(data.message || '注册失败')
    }
  } catch (error) {
    console.error('注册失败:', error)
    message.error(error.message || '注册失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取邀请者信息
const fetchInviterInfo = async (code) => {
  try {
    const response = await getInviterInfo(code)
    if (response.status === 'success') {
      inviterInfo.value = response.data.inviter
    }
  } catch (error) {
    console.error('获取邀请者信息失败:', error)
  }
}

// 监听邀请码变化
watch(() => form.inviteCode, async (newCode) => {
  if (newCode && newCode.length >= 6) {
    await fetchInviterInfo(newCode)
  } else {
    inviterInfo.value = null
  }
})

// 页面加载时检查URL中的邀请码
onMounted(() => {
  const inviteCode = route.query.invite
  if (inviteCode) {
    form.inviteCode = inviteCode
    inviteCodeFromUrl.value = true
    fetchInviterInfo(inviteCode)
  }
})

// 组件卸载时清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
})
</script>

<style scoped lang="scss">
.register-form {
  .code-input-group {
    display: flex;
    align-items: center;
  }
  
  .form-footer {
    text-align: center;
    
    a {
      color: #1890ff;
      cursor: pointer;
      
      &:hover {
        text-decoration: underline;
      }
    }
  }

  .inviter-info {
    margin-top: 8px;
    padding: 8px 12px;
    background: #f6ffed;
    border: 1px solid #b7eb8f;
    border-radius: 6px;
    
    .inviter-tip {
      color: #52c41a;
      font-size: 14px;
      font-weight: 500;
    }
  }
}
</style> 